package lpg.tool.templatec;

import java.io.File;
import java.io.FileFilter;

public class BatchTemplatec
{
    public static void main(String[] args)
    {
        // If only "lpg.tool.templatec.BatchTemplatec" is typed,
        // we display the help screen.
        if (args.length != 1 || args[0].startsWith("?"))
        {
            usage();
            return;
        }

        File dir = new File(args[0]);
        if (!dir.isDirectory())
        {
            System.out.println("***Error: \"" + args[0] + "\" is not a directory.");
            return;
        }

        compile(args[0], "", dir);
    }

    private static void compile(String root, String prefix, File dir)
    {
        File[] files = dir.listFiles(templateFilter);
        if (files != null)
        {
            for (File file : files)
            {
                String fileName = file.getName();
                if (file.isFile())
                {
                    String name = fileName.substring(0, fileName.length() - 2);
                    Main.main(new String[]
                            {
                                "-c",
                                prefix.length() == 0 ? name : prefix + '.' + name,
                                "-d",
                                root,
                                file.getAbsolutePath()
                            });
                }
                else
                    compile(root, prefix.length() == 0 ? fileName : prefix + '.' + fileName, file);
            }
        }
    }

    private static void usage()
    {
        System.out.println();
        System.out.println("Usage: lpg.tool.templatec.BatchTemplatec <dir>");
    }

    private static final FileFilter templateFilter =
            new FileFilter()
            {
                public boolean accept(File pathname)
                {
                    return !pathname.isHidden() &&
                           (pathname.isDirectory() ||
                           (pathname.isFile() && pathname.getName().endsWith(".t")));
                }
            };

}
